package com.fy56.platform.logistics.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fy56.platform.logistics.common.BaseEntity;
import com.fy56.platform.logistics.common.Page;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.mapper.OrderMapper;
import com.fy56.platform.logistics.mapper.ReceiverContactInfoMapper;
import com.fy56.platform.logistics.mapper.SenderContactInfoMapper;
import com.fy56.platform.logistics.model.*;
import com.fy56.platform.logistics.service.web.IColumnExtService;
import com.fy56.platform.logistics.service.wx.*;
import com.fy56.platform.logistics.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zeus.base.privilege.model.TbCompany;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.net.SocketTimeoutException;
import java.util.*;

import static com.fy56.platform.logistics.utils.HttpUtil.setHeader;

/**
 * Created by lml on 2018/2/25.
 */
@Service
public class OrderServiceImpl implements IOrderService {
    private static Logger log = Logger.getLogger(OrderServiceImpl.class);
    @Autowired
    ILogisticsSlaveBasisService iLogisticsBasisService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ICompanyInfoService iCompanyInfoService;
    @Autowired
    private ReceiverContactInfoMapper receiverContactInfoMapper;
    @Autowired
    private SenderContactInfoMapper senderContactInfoMapper;

    @Autowired
    private IVipBankService iVipBankService;

    @Autowired
    private IColumnExtService iColumnExtService;
    @Autowired
    private IPayOrderService iPayOrderService;


    @Override
    public Integer updateById(Order order) {

        //保存收货人信息
        saveReceiverContact(order);

        //保存发货人信息
        saveSenderContact(order);


        return orderMapper.updateById(order);
    }

    @Override
    public Integer updateUploadFlag(Order order) {


        return orderMapper.updateUploadFlag(order);
    }

    @Override
    public Integer deleteById(Order order) {
        return orderMapper.deleteById(order);
    }

    @Override
    public Integer save(Order order) {

        //保存订单
        Integer result = orderMapper.insert(order);

        //保存收货人信息
        if (order.getIsSaveReceiver() == 1) {
            saveReceiverContact(order);
        }

        //保存发货人信息
        if (order.getIsSaveSender() == 1) {
            saveSenderContact(order);
        }

        return result;
    }

    /**
     * 保存联系人
     *
     * @param order
     */
    private void saveReceiverContact(Order order) {
        ReceiverContactInfo receiverContactInfo = new ReceiverContactInfo();
        receiverContactInfo.setVipMemberId(Long.valueOf(order.getUserId()));
        receiverContactInfo.setContactName(order.getReceiver());
        receiverContactInfo.setContactMobile(order.getReceiverMobile());
        if (order.getReceiverLongitude()!=null){
            receiverContactInfo.setConsigneeLongitude(order.getReceiverLongitude());
        }
        if (order.getReceiverLatitude()!=null){
            receiverContactInfo.setConsigneeLatitude(order.getReceiverLatitude());
        }
        if (order.getIsDefaultReceiver() == 1) {
            receiverContactInfo.setIsDefault(1);
            //更新所有收货联系人记录的是否默认为 0
            receiverContactInfoMapper.updateDefaultFlag(Long.valueOf(order.getUserId()));
        }
        ReceiverContactInfo dbModel = receiverContactInfoMapper.getExistsByVipMemberIdAndMobile(receiverContactInfo);//查询联系人是否存在
        if (dbModel == null) {
            //不存在该联系人，保存
            receiverContactInfo.setId(Long.valueOf(IdWorkerTools.getInstance().getId()));
            receiverContactInfo.setContactAddress(order.getReceiverAddress());
            receiverContactInfo.setContactIdCard(order.getConsigneeIdCard());
            receiverContactInfo.setCreateTime(new Date());
            receiverContactInfoMapper.insert(receiverContactInfo);
        } else {
            //存在该联系人，修改
            receiverContactInfo.setId(dbModel.getId());
            receiverContactInfo.setContactAddress(order.getReceiverAddress());
            receiverContactInfo.setContactIdCard(order.getConsigneeIdCard());
            receiverContactInfo.setUpdateTime(new Date());
            receiverContactInfoMapper.updateByPrimaryKey(receiverContactInfo);
        }
    }

    /**
     * 保存联系人
     *
     * @param order
     */
    private void saveSenderContact(Order order) {
        SenderContactInfo model = new SenderContactInfo();
        model.setVipMemberId(Long.valueOf(order.getUserId()));
        model.setContactName(order.getSender());
        model.setContactMobile(order.getSenderMobile());
        if (order.getIsDefaultSender() == 1) {
            model.setIsDefault(1);
            //更新所有收货联系人记录的是否默认为 0
            senderContactInfoMapper.updateDefaultFlag(Long.valueOf(order.getUserId()));
        }
        SenderContactInfo dbModel = senderContactInfoMapper.getExistsByVipMemberIdAndMobile(model);//查询联系人是否存在
        if (dbModel == null) {
            //不存在该联系人，保存
            model.setContactAddress(order.getSenderAddress());
            model.setLatitude(order.getSenderLatitude());
            model.setLongitude(order.getSenderLongitude());
            model.setContactIdCard(order.getConsignerIdCard());
            model.setCreateTime(new Date());
            senderContactInfoMapper.insert(model);
        } else {
            //存在该联系人，修改
            model.setId(dbModel.getId());
            model.setContactAddress(order.getSenderAddress());
            model.setLatitude(order.getSenderLatitude());
            model.setLongitude(order.getSenderLongitude());
            model.setContactIdCard(order.getConsignerIdCard());
            model.setUpdateTime(new Date());
            senderContactInfoMapper.updateByPrimaryKey(model);
        }
    }

    @Override
    public Page<Map<String, Object>> queryOrderList(Map<String, Object> params) {
        BaseEntity entity = new BaseEntity();
        entity.setTable_(" pre_accept_order p left join company t on p.tenant_id = t.id ");
        entity.setColumn_(" p.id,\n" +
                "\tp.order_number orderNumber,\n" +
                "\tp.goods_number goodsNumber,\n" +
                "\tp.manual_number manualNumber,\n" +
                "\tp.tenant_id tenantId,\n" +
                "\tp.tenant_code tenantCode,\n" +
                "\tp.pick_up_way pickUpWay,\n" +
                "\tp.receiver,\n" +
                "\tp.receiver_mobile receiverMobile,\n" +
                "\tp.receiver_address receiverAddress,\n" +
                "\tp.goods_name goodsName,\n" +
                "\tp.number_of_goods numberOfGoods,\n" +
                "\tFORMAT(p.collection_of_money,2) collectionOfMoney,\n" +
                "\tp.package_type packageType,\n" +
                "\tp.remarks,\n" +
                "\tp.sender,\n" +
                "\tp.sender_mobile senderMobile,\n" +
                "\tp.sender_address senderAddress,\n" +
                "\tp.bank_name bankName,\n" +
                "\tp.bank_account bankAccount,\n" +
                "\tp.bank_card_number bankCardNumber,\n" +
                "\tp.vip_number vipNumber,\n" +
                "\tp.pick_up_code pickUpCode,\n" +
                "\tp.place_of_loading placeOfLoading,\n" +
                "\tp.send_company sendCompany,\n" +
                "\tp.unload_place unloadPlace,\n" +
                "\tp.receive_company receiveCompany,\n" +
                "\tp.user_id userId,\n" +
                "\tp.generate_flag generateFlag,\n" +
                "\tp.weight,\n" +
                "\tp.bulk,\n" +
                "\tp.sendWay,\n" +
                "\tp.pay_way payWay,\n" +
                "\tp.resource,\n" +
                "\tp.receiverCompany receiverCompany,\n" +
                "\tp.order_number orderNumber,\n" +
                "\tFORMAT(p.cashOnDelivery,2) cashOnDelivery,\n" +
                "\tFORMAT(p.freight,2) freight,\n" +
                "\tDATE_FORMAT(\n" +
                "\t\tp.order_create_time,\n" +
                "\t\t'%Y-%m-%d'\n" +
                "\t) AS orderCreateTime,\n" +
                "\tt. NAME AS tenantName ");
        setWhereSql(entity, params);
        entity.setOrder_(" order by order_create_time desc ");
        Integer page = 1;
        if (params.get("pageIndex") != null) {
            page = Integer.valueOf(params.get("pageIndex").toString());
        }
        Integer pageSize = 10;
        if (params.get("pageCount") != null) {
            pageSize = Integer.valueOf(params.get("pageCount").toString());
        }
        Page<Map<String, Object>> result = iLogisticsBasisService.findPage(entity, page, pageSize);
        return result;
    }

    private void setWhereSql(BaseEntity entity, Map<String, Object> params) {
        String whereSql = " where 1=1 ";
        Object startDate = params.get("startDate");
        if (startDate != null && StringUtil.isNotEmpty(startDate.toString())) {
            whereSql += " and order_create_time >= '" + startDate + " 00:00:00' ";
        }
        Object endDate = params.get("endDate");
        if (endDate != null && StringUtil.isNotEmpty(endDate.toString())) {
            whereSql += " and order_create_time <= '" + endDate + " 23:59:59' ";
        }
        Object pickUpCode = params.get("pickUpCode");
        if (pickUpCode != null && StringUtil.isNotEmpty(pickUpCode.toString())) {
            whereSql += " and p.pick_up_code = '" + pickUpCode + "' ";
        }
        Object unloadPlace = params.get("unloadPlace");
        if (unloadPlace != null && StringUtil.isNotEmpty(unloadPlace.toString())) {
            whereSql += " and p.unload_place = '" + unloadPlace + "' ";
        }
        Object receiver = params.get("receiver");
        if (receiver != null && StringUtil.isNotEmpty(receiver.toString())) {
            whereSql += " and p.receiver = '" + receiver + "' ";
        }
        Object generateFlag = params.get("generateFlag");
        if (generateFlag != null && StringUtil.isNotEmpty(generateFlag.toString())) {
            whereSql += " and p.generate_flag = '" + generateFlag + "' ";
        }
        Object userId = params.get("userId");
        if (userId != null && StringUtil.isNotEmpty(userId.toString())) {
            whereSql += " and p.user_id = " + userId + " ";
        }
        //发货人手机
        Object senderMobile = params.get("senderMobile");
        if (senderMobile != null && StringUtil.isNotEmpty(senderMobile.toString())) {
            whereSql += " and p.sender_mobile = '" + senderMobile + "' ";
        }
        //收货人手机
        Object receiverMobile = params.get("receiverMobile");
        if (receiverMobile != null && StringUtil.isNotEmpty(receiverMobile.toString())) {
            whereSql += " and p.receiver_mobile = '" + receiverMobile + "' ";
        }
        //金融代码
        Object code = params.get("code");
        if (code != null && StringUtil.isNotEmpty(code.toString())) {
            whereSql += " and p.tenant_code = '" + code + "' ";
        }
        entity.setWhere_(whereSql);
    }

    @Override
    public Order selectByPrimaryKey(Long id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public ResultModel delete(Order entity) {
        return null;
    }

    @Override
    public List<Order> findList(Order user) {
        return null;
    }

    @Override
    public ResultModel insert(Order entity) {
        return null;
    }

    @Override
    public ResultModel update(Order entity) {
        return null;
    }

    @Override
    public ResultModel insertSelective(Order entity) {
        return null;
    }

    @Override
    public ResultModel updateSelective(Order entity) {
        return null;
    }

    @Override
    public Order get(Order entity) {
        return null;
    }

    @Override
    public ResultModel delete(Long id) {
        return null;
    }

    /**
     * 根据金融代码和用户ID获得下单的基本信息
     * 1.目的地
     * 2.业务相关设置 : 小程序代收是否必须输入银行信息
     * 3.业务相关设置 : 小程序有代收货款必须与默认开户银行一致
     * 4.业务相关设置 : 默认银行
     * 5.业务相关设置 : 配送（提货）方式
     * 6.默认的付款方式
     * 7.默认的配送（提货）方式
     * 8.付款方式
     * 9.包装样式
     * 10.发货人
     * 11.默认发货人
     * 12.收货人
     * 13.默认收货人
     * 14.寄件网点（从认证中心获取的子公司信息）
     * 15.银行信息
     * 16.常用货物名
     *
     * @param code      金融代码
     * @param userId    用户ID
     * @param latitude  纬度
     * @param longitude 经度
     * @return
     */
    @Override
    public Map<String, Object> getOrderBaseInfo(String code, Long userId, String latitude, String longitude, String openId,Company company) {

        //如果是F6系统，则帐套名称和组织代码必须传
        if(company==null){
            company = iCompanyInfoService.getCompanyByCode(code);
        }
        if (company == null || StringUtil.isEmpty(company.getUrl())) {
            throw new NullPointerException("未设置租户信息");
        }
        if (openId == null) {
            openId = "";
        }
        String url = company.getUrl() + "/orderBaseInfo?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode() + "&userId=" + openId;


        Long begin = System.currentTimeMillis();//开始时间
        //初始化返回值
        Map<String, Object> obj = Maps.newHashMap();
        Map<String, Object> res = JSON.parseObject(HttpUtil.get(url));
        if (res != null && res.get("content") != null) {
            obj = JSON.parseObject(res.get("content").toString());
        }
        Long end = System.currentTimeMillis();//结束时间

        log.info("getOrderBaseInfo  orderBaseInfo:" + (end - begin) + "毫秒。");

        //new 新卸货地点
        //http://f6test.feiyang56.cn:1880/WeChat.asq?/orderBaseInfo?accountName=F6TEST&organizationCode=fyrjgs&userId=779399832573374509
        String unloadPlacesUrl = company.getUrl() + "/orderBaseInfo?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode() + "&&userId=" + userId;


        begin = System.currentTimeMillis();//开始时间
        //设置收货人信息
        List<ReceiverContactInfo> receiverContactInfos = Lists.newArrayList();
        if (userId != null) {
            receiverContactInfos = receiverContactInfoMapper.selectByVipMemberId(userId);
        }
        end = System.currentTimeMillis();//结束时间
        log.info("getOrderBaseInfo 设置收货人信息:" + (end - begin) + "毫秒。");

        obj.put("receiverContactInfos", receiverContactInfos);

        //设置默认收货人
        for (ReceiverContactInfo info : receiverContactInfos) {
            if (info.getIsDefault() == 1) {
                obj.put("defaultReceiver", info);
                break;
            }
        }
        if (obj.get("defaultReceiver") == null) {
            obj.put("defaultReceiver", null);
        }


        begin = System.currentTimeMillis();//开始时间
        //设置发货人信息
        List<SenderContactInfo> senderContactInfos = Lists.newArrayList();
        if (userId != null) {
            senderContactInfos = senderContactInfoMapper.selectByVipMemberId(userId);
        }
        obj.put("senderContactInfos", senderContactInfos);
        end = System.currentTimeMillis();//结束时间
        log.info("getOrderBaseInfo 设置发货人信息:" + (end - begin) + "毫秒。");

        //设置默认发货人
        for (SenderContactInfo info : senderContactInfos) {
            if (info.getIsDefault() == 1) {
                obj.put("defaultSender", info);
                break;
            }
        }
        if (obj.get("defaultSender") == null) {
            obj.put("defaultSender", null);
        }

        begin = System.currentTimeMillis();//开始时间
        //寄件网点（从认证中心获取的子公司信息）
        List<Company> companyList = iCompanyInfoService.getWebList(code, longitude, latitude,company);
        if (CollectionUtils.isEmpty(companyList)) {
            obj.put("webList", Lists.newArrayList());
        } else {
            obj.put("webList", companyList);
        }
        end = System.currentTimeMillis();//结束时间
        log.info("getOrderBaseInfo 寄件网点:" + (end - begin) + "毫秒。");


        //20200403寄件网点改成从F6获取，重新计算坐标距离
        try {
            begin = System.currentTimeMillis();//开始时间
            JSONArray sendCompanys = JSONArray.parseArray(obj.get("sendCompanys") + "");
            List<Company> f6CompanyList = iCompanyInfoService.getF6WebList(sendCompanys, longitude, latitude);
            if (CollectionUtils.isEmpty(companyList)) {
                obj.put("webF6List", Lists.newArrayList());
            } else {
                obj.put("webF6List", f6CompanyList);
            }
            end = System.currentTimeMillis();//结束时间
            log.info("getOrderBaseInfo 寄件网点F6:" + (end - begin) + "毫秒。");
        } catch (Exception e) {

        }

        //设置绑定的银行卡信息
        begin = System.currentTimeMillis();//开始时间
        List<VipBank> vipBankList = Lists.newArrayList();
        if (userId != null) {
            vipBankList = iVipBankService.select(userId);
        }
        end = System.currentTimeMillis();//结束时间
        log.info("getOrderBaseInfo VipBank:" + (end - begin) + "毫秒。");
        obj.put("vipBankList", vipBankList);


        begin = System.currentTimeMillis();//开始时间
        //设置字段扩展
        List<ColumnExt> orderColumnExtList = Lists.newArrayList();
        Map<String, Object> parameter = Maps.newHashMap();
        parameter.put("companyId", company.getId());
        parameter.put("type", 0);
        if (userId != null) {
            orderColumnExtList = iColumnExtService.findColumnExtList(parameter);
        }
        end = System.currentTimeMillis();//结束时间
        log.info("getOrderBaseInfo 设置字段扩展:" + (end - begin) + "毫秒。");
        obj.put("orderColumnExtList", orderColumnExtList);

        //获取-常用货物名
        begin = System.currentTimeMillis();//开始时间
        List<String> goodsNames = new ArrayList<>();
        try {
            goodsNames = getGoodsNameInfoBSOrF6(code,company);
        } catch (Exception e) {
            e.printStackTrace();
        }
        obj.put("selGoodsNames", goodsNames);
         end = System.currentTimeMillis();//结束时间
        log.info("getOrderBaseInfo 常用货物名:" + (end - begin) + "毫秒。");
        return obj;
    }

    /**
     * 根据发货人手机号和金融代码获取一卡通信息
     *
     * @param code
     * @param mobile
     * @return
     */
    @Override
    public ResultModel getVipCardInfo(String code, String mobile) {

        //如果是F6系统，则帐套名称和组织代码必须传
        Company company = iCompanyInfoService.getCompanyByCode(code);
        if (StringUtil.isEmpty(company.getUrl())) {
            return ResultModel.error("未设置租户信息");
        }
        String url = company.getUrl() + "/orderBaseInfo/getVipCardInfo?mobile=" + mobile;
        if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {
            url += "&accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        System.out.print("一卡通列表请求路径：" + url);
        //初始化返回值
        Map<String, Object> res = JSON.parseObject(HttpUtil.get(url));
        System.out.print("一卡通列表返回结果：" + res);
        if (res != null && "SUCCESS".equals(res.get("msg"))) {
            return ResultModel.ok(res.get("content"));
        }

        return ResultModel.error(res.get("msg") == null ? "服务端出错" : res.get("msg").toString());
    }

    /**
     * 根据发货人一卡通号和金融代码获取一卡通信息
     *
     * @param code
     * @param vipCardNo
     * @return
     */
    @Override
    public ResultModel getVipCardInfo2(String code, String vipCardNo) {

        //如果是F6系统，则帐套名称和组织代码必须传
        Company company = iCompanyInfoService.getCompanyByCode(code);
        if (StringUtil.isEmpty(company.getUrl())) {
            return ResultModel.error("未设置租户信息");
        }
        String url = company.getUrl() + "/orderBaseInfo/getVipCardInfo?vipNo=" + vipCardNo;
        if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {
            url += "&accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        System.out.print("一卡通列表请求路径：" + url);
        //初始化返回值
        Map<String, Object> res = JSON.parseObject(HttpUtil.get(url));
        System.out.print("一卡通列表返回结果：" + res);
        if (res != null && "SUCCESS".equals(res.get("msg"))) {
            return ResultModel.ok(res.get("content"));
        }

        return ResultModel.error(res.get("msg") == null ? "服务端出错" : res.get("msg").toString());
    }

    /**
     * 把对象封装成map做为参数传给平台
     *
     * @param map
     * @return
     */
    private String setParam(Map<String, String> map) {
        String param = "param=" + JSONObject.toJSONString(map);
        return param;
    }

    /**
     * 小程序主页订单信息（10条正式订单，10条预受理单）
     *
     * @param senderMobile
     * @return
     */
    @Override
    public List<Order> searchOrderForIndex(String code, String userId, String senderMobile) throws Exception {
        Long begin = System.currentTimeMillis();//开始时间
        //初始化返回值
        List<Order> orderList = Lists.newArrayList();

        //金融代码不为空：定制版；为空时：公版
        if (StringUtil.isNotEmpty(code)&&!"FYGB2020".equals(code)) {

            //初始化参数
            Map<String, Object> map = Maps.newHashMap();
            map.put("code", code);
            map.put("userId", userId);
            map.put("mobile", senderMobile);
            map.put("flag", 0);
            map.put("currentPage", 1);
            map.put("pageSize", 10);
            map.put("startDate", DateUtil.getMonthChange(new Date(), -1, null));
            map.put("endDate", DateUtil.turnDateToString(new Date(), "yyyy-MM-dd"));

            //从F6或BS服务端获取10条正式订单（条件：一个月内，用该手机号发货或者收货的10条记录）
            orderList.addAll(getOrderListFromBusinessSys(map));

            //从F6或BS服务端获取10条正式订单（条件：一个月内，用该手机号发货或者收货的10条记录）
            orderList.addAll(getPreOrderListFromBusinessSys(map));
        } else {

            //从货物跟踪平台获取10条主订单（条件：一个月内，用该手机号发货或者收货的10条记录）
            orderList.addAll(getOrderListFromGoodsTracePlatForm(code, senderMobile, 0));

            //获取10条预受理单(本地获取)
            Order searchModel = new Order();
            searchModel.setTenantCode(code);
            searchModel.setUserId(userId);
            orderList.addAll(orderMapper.searchOrderForIndex(searchModel));
        }
        Long end = System.currentTimeMillis();//结束时间
        System.out.print("首页订单总用时：" + (end - begin) + "毫秒。");
        return orderList;
    }


    /**
     * 小程序主页公版订单信息（10条正式订单，10条预受理单）
     *
     * @param senderMobile
     * @return
     */
    @Override
    public List<Order> searchOrderPubVersionForIndex(String code, String userId, String senderMobile) throws Exception {
        //初始化返回值
        List<Order> orderList = Lists.newArrayList();

        //获取10条预受理单(本地获取)
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", userId);
        paramMap.put("tenantCode", code);
        paramMap.put("generateFlag", "1");
        orderList.addAll(orderMapper.searchOrderForIndexPage(paramMap));

        //获取10条已受理单(本地获取)
        paramMap.put("generateFlag", "0");
        orderList.addAll(orderMapper.searchOrderForIndexPage(paramMap));
        return orderList;
    }

    /**
     * 我的运单（已受理）：从F6或BS服务端获取最新的10条正式订单
     * 参数说明：
     * 1. code 金融代码
     * 2. userId 当前请求的用户ID
     * 3. mobile 手机号
     * 4. flag 手机类型(0：该手机号只作为发货人手机；1：该手机号作为收货人手机；2：该手机号作为发货人或者收货人手机)
     * 5. currentPage 当前页数
     * 6. pageSize 每页显示个数
     * 7. startDate 开始日期 默认一个月
     * 8. endDate 结束日期 默认一个月
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<Order> getOrderListFromBusinessSys(Map<String, Object> params) throws Exception {

        //初始化返回值
        List<Order> list = Lists.newArrayList();

        //根据金融代码获取公司信息，如果获取不到，抛出异常
        Company company = iCompanyInfoService.getCompanyByCode(params.get("code").toString());
        if (company == null) {
            throw new Exception("该企业[" + params.get("code").toString() + "]已被删除！");
        }
        Long begin = System.currentTimeMillis();//开始时间
        //请求地址(如果是F6系统，则帐套名称和组织代码必须传)
        String url = company.getUrl() + "/orderBaseInfo/getOrderListPage?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();

        //如果开始日期和结束为空，则默认查询一个月的数据
        if (params.get("startDate") == null || StringUtil.isEmpty(params.get("startDate").toString())) {
            //开始日期
            params.put("startDate", DateUtil.getMonthChange(new Date(), -1, null));
        }
        if (params.get("endDate") == null || StringUtil.isEmpty(params.get("endDate").toString())) {
            //结束日期
            params.put("endDate", DateUtil.turnDateToString(new Date(), "yyyy-MM-dd"));
        }

        //请求处理
        String result = null;
        try {
            log.info("getOrderListFromBusinessSys url:" + url + "&param=" + params.toString());
            result = HttpClientUtils.post(url + "&param=" + JSONObject.toJSONString(params), null, setHeader(), 20000, 20000);
            log.info("getOrderListPage:result:"+result);
            Long end = System.currentTimeMillis();//结束时间
            log.info("我的运单已受理请求F6用时：" + (end - begin) + "毫秒。");
            //            result = HttpUtil.postWidthParamName(url,"param",params);
            if (StringUtil.isNotEmpty(result)) {
                Map<String, Object> resultMap = JSON.parseObject(result);
                if ("SUCCESS".equals(resultMap.get("msg").toString())) {
                    JSONArray array = JSONArray.parseArray(JSON.parseObject(resultMap.get("content").toString()).get("list").toString());
                    //对象转换
                    list = copyListForBSOrF6((List) array);

                } else {
                   // throw new Exception("从F6或BS服务端获取最新的10条正式订单失败！" + resultMap.get("msg").toString());
                }
            } else {
                //throw new Exception("请求F6或BS服务端失败或无返回值！");
            }
        } catch (JSONException e) {
            throw new Exception("请求F6或BS服务端出错，请联系管理员！", e);
        } catch (SocketTimeoutException e) {
            throw new Exception("请求F6或BS服务端超时，请联系管理员！", e);
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
        }
        Long end = System.currentTimeMillis();//结束时间
        System.out.print("我的运单已受理总用时：" + (end - begin) + "毫秒。");
        return list;
    }

    /**
     * 我的运单（未受理）：从F6或BS服务端获取最新的10条预受理单
     * 参数说明：
     * 1. code 金融代码
     * 2. userId 当前请求的用户ID
     * 3. currentPage 当前页数
     * 4. pageSize 每页显示个数
     * 5. startDate 开始日期 默认一个月
     * 6. endDate 结束日期 默认一个月
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<Order> getPreOrderListFromBusinessSys(Map<String, Object> params) throws Exception {
        Long begin = System.currentTimeMillis();//开始时间
        //初始化返回值
        List<Order> list = Lists.newArrayList();

        //根据金融代码获取公司信息，如果获取不到，抛出异常
        Company company = iCompanyInfoService.getCompanyByCode(params.get("code").toString());
        if (company == null) {
            throw new Exception("该企业[" + params.get("code").toString() + "]已被删除！");
        }

        //请求地址(如果是F6系统，则帐套名称和组织代码必须传)
        String url = company.getUrl() + "/orderBaseInfo/getPreOrderListPage?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();

        //如果开始日期和结束为空，则默认查询一个月的数据
        if (params.get("startDate") == null || StringUtil.isEmpty(params.get("startDate").toString())) {
            //开始日期
            params.put("startDate", DateUtil.getMonthChange(new Date(), -1, null));
        }
        if (params.get("endDate") == null || StringUtil.isEmpty(params.get("endDate").toString())) {
            //结束日期
            params.put("endDate", DateUtil.turnDateToString(new Date(), "yyyy-MM-dd"));
        }

        //请求处理
        String result = null;
        try {
            System.out.println("getPreOrderListFromBusinessSys url:" + url + "&param=" + params.toString());
            Map<String, String> header = Maps.newHashMap();
            header.put("Authorization", "ignore");
            header.put("Content-type", "application/x-www-form-urlencoded");
            header.put("charset", "utf-8");
            result = HttpClientUtils.post(url + "&param=" + JSONObject.toJSONString(params), null, setHeader(), 20000, 20000);
            log.info("getPreOrderListPage:result:"+result);
            Long end = System.currentTimeMillis();//结束时间
            System.out.print("我的运单未受理请求F6用时：" + (end - begin) + "毫秒。");
            if (StringUtil.isNotEmpty(result)) {
                Map<String, Object> resultMap = JSON.parseObject(result);
                if ("SUCCESS".equals(resultMap.get("msg").toString())) {
                    list = JSON.parseObject(resultMap.get("content").toString()).getJSONArray("list").toJavaList(Order.class);
                } else {
                    throw new Exception("从F6或BS服务端获取最新的10条受理单失败！" + resultMap.get("msg").toString());
                }
            } else {
                throw new Exception("请求F6或BS服务端失败或无返回值！");
            }
        } catch (JSONException e) {
            throw new Exception("请求F6或BS服务端出错，请联系管理员！", e);
        } catch (SocketTimeoutException e) {
            throw new Exception("请求F6或BS服务端超时，请联系管理员！", e);
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
        }
        Long end = System.currentTimeMillis();//结束时间
        System.out.print("我的运单未受理总用时：" + (end - begin) + "毫秒。");
        return list;
    }

    /**
     * 货物跟踪平台查询主订单（条件：一个月内，用该手机号发货的10条记录，如果flag=1，则是用该手机号发货或者收货的10条记录）
     *
     * @param code   金融代码
     * @param mobile 手机号
     * @param flag   手机类型(0：该手机号只作为发货人手机；1：该手机号作为收货人手机；2：该手机号作为发货人或者收货人手机)
     * @return
     * @throws Exception
     */
    private List<Order> getOrderListFromGoodsTracePlatForm(String code, String mobile, int flag) throws Exception {

        //初始化返回值
        List<Order> list = Lists.newArrayList();

        Map<String, String> paramMap = Maps.newHashMap();
        //发货人手机号
        paramMap.put("consignorTelephoneNumber", mobile == null ? "" : mobile);
        //金融代码
        paramMap.put("tenant", code == null ? "" : code);
        //当前页数
        paramMap.put("currentPage", "1");
        //每页显示个数
        paramMap.put("pageNumber", "10");
        //开始日期
        paramMap.put("startDate", DateUtil.getMonthChange(new Date(), -1, null) + " 00:00:00");
        //结束日期
        paramMap.put("endDate", DateUtil.turnDateToString(new Date(), "yyyy-MM-dd") + " 00:00:00");

        //请求处理
        String result = null;
        try {
            result = HttpClientUtils.postParameters(StaticUtil.TRACE_OHM_ORDER_URL, setParam(paramMap));
            if (StringUtil.isNotEmpty(result)) {
                Map<String, Object> resultMap = JSON.parseObject(result);
                if (Boolean.valueOf(resultMap.get("success").toString())) {
                    JSONArray array = JSON.parseObject(resultMap.get("object").toString()).getJSONArray("list");
                    //将OhmOrder对象转换成Order对象
                    list = copyList((List) array);
                } else {
                    throw new Exception("货物跟踪平台查询主订单失败！" + resultMap.get("msg").toString());
                }
            } else {
                throw new Exception("请求货物跟踪平台失败或无返回值！");
            }
        } catch (JSONException e) {
            throw new Exception("请求货物跟踪平台出错，请联系管理员！", e);
        } catch (SocketTimeoutException e) {
            throw new Exception("请求货物跟踪平台超时，请联系管理员！", e);
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
        }

        return list;
    }

    /**
     * 货物跟踪平台查询主订单（条件：一个月内，用该手机号发货的10条记录，如果flag=1，则是用该手机号发货或者收货的10条记录）
     *
     * @param code   金融代码
     * @param mobile 手机号
     * @param flag   手机类型(0：该手机号只作为发货人手机；1：该手机号作为收货人手机；2：该手机号作为发货人或者收货人手机)
     * @return
     * @throws Exception
     */
    @Override
    public List<Order> getGoodsTraceList(String code, String mobile, int flag) throws Exception {

        //初始化返回值
        List<Order> list = Lists.newArrayList();

        Map<String, String> paramMap = Maps.newHashMap();
        //发货人手机号
        paramMap.put("consignorTelephoneNumber", mobile == null ? "" : mobile);
        //金融代码
        paramMap.put("tenant", code == null ? "" : code);
        //当前页数
        paramMap.put("currentPage", "1");
        //每页显示个数
        paramMap.put("pageNumber", "10");
        //开始日期
        paramMap.put("startDate", DateUtil.getMonthChange(new Date(), -1, null) + " 00:00:00");
        //结束日期
        paramMap.put("endDate", DateUtil.turnDateToString(new Date(), "yyyy-MM-dd") + " 00:00:00");

        //请求处理
        String result = null;
        try {
            result = HttpClientUtils.postParameters(StaticUtil.TRACE_OHM_ORDER_URL, setParam(paramMap));
            if (StringUtil.isNotEmpty(result)) {
                Map<String, Object> resultMap = JSON.parseObject(result);
                if (Boolean.valueOf(resultMap.get("success").toString())) {
                    JSONArray array = JSON.parseObject(resultMap.get("object").toString()).getJSONArray("list");
                    //将OhmOrder对象转换成Order对象
                    list = toOrderList((List) array);
                } else {
                    throw new Exception("货物跟踪平台查询主订单失败！" + resultMap.get("msg").toString());
                }
            } else {
                throw new Exception("请求货物跟踪平台失败或无返回值！");
            }
        } catch (JSONException e) {
            throw new Exception("请求货物跟踪平台出错，请联系管理员！", e);
        } catch (SocketTimeoutException e) {
            throw new Exception("请求货物跟踪平台超时，请联系管理员！", e);
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
        }

        return list;
    }
    /**
     * 货物跟踪平台查询主订单（条件：一个月内，用该手机号发货的10条记录，如果flag=1，则是用该手机号发货或者收货的10条记录）
     *
     * @param code   金融代码
     * @param mobile 手机号
     * @param flag   手机类型(0：该手机号只作为发货人手机；1：该手机号作为收货人手机；2：该手机号作为发货人或者收货人手机)
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object>  getGoodsTraceListNew(String code, String mobile, int flag) throws Exception {

        //初始化返回值
        List<Order> list = Lists.newArrayList();

        Map<String, String> paramMap = Maps.newHashMap();
        if (0==flag){
            //发货人手机号
            paramMap.put("consignorTelephoneNumber", mobile == null ? "" : mobile);
        }else{
            //收货人手机号
            paramMap.put("consigneeTelephoneNumber", mobile == null ? "" : mobile);
        }
        //金融代码
        paramMap.put("tenant", code == null ? "" : code);
        //当前页数
        paramMap.put("currentPage", "1");
        //每页显示个数
        paramMap.put("pageNumber", "10");
        //开始日期
        paramMap.put("startDate", DateUtil.getMonthChange(new Date(), -1, null) + " 00:00:00");
        //结束日期
        paramMap.put("endDate", DateUtil.turnDateToString(new Date(), "yyyy-MM-dd") + " 23:59:59");
        Map<String, Object> resultMap =Maps.newHashMap();
        //请求处理
        String result = null;
        try {
            result = HttpClientUtils.postParameters(StaticUtil.TRACE_OHM_ORDER_URL, setParam(paramMap));
            if (StringUtil.isNotEmpty(result)) {
                resultMap = JSON.parseObject(result);

            } else {
                throw new Exception("请求货物跟踪平台失败或无返回值！");
            }
        } catch (JSONException e) {
            throw new Exception("请求货物跟踪平台出错，请联系管理员！", e);
        } catch (SocketTimeoutException e) {
            throw new Exception("请求货物跟踪平台超时，请联系管理员！", e);
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
        }

        return resultMap;
    }
    /**
     * 同步预受理单至BS和F6服务
     *
     * @param order
     */
    @Override
    public String syncPreOrder(Order order) {

        //如果是F6系统，则不同步数据
        Company company = iCompanyInfoService.getCompanyByCode(order.getTenantCode());
        if (company == null || StringUtil.isEmpty(company.getUrl())) {
            throw new NullPointerException("未设置租户信息");
        }
        //初始化请求参数
        Map<String, String> postParams = Maps.newHashMap();

        //BS同步数据地址
        String url = company.getUrl() + "/preAcceptOrder/syncPreOrder";

        //F6同步数据地址
        if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {
            url = company.getUrl() + "/orderBill/add?databaseId=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        postParams.put("data", JSONObject.toJSONString(order, SerializerFeature.WriteMapNullValue));
        String result = HttpAsyncUtil.asyncPost(url, postParams, setHeader());
        if (StringUtil.isNotEmpty(result)) {
            ResultModel model = JSON.parseObject(result, ResultModel.class);
            if (200 == model.getCode()) {
                if ("SUCCESS".equals(model.getMsg())) {
                    return null;
                } else {
                    return model.getMsg();
                }
            } else {
                return "请求BS，F6服务端出错！";
            }
        }
        return null;
    }

    /**
     * 小程序运单详情（已处理时，根据票号查询业务系统的订单数据，未处理查询预受理单数据）
     *
     * @param code    金融代码
     * @param id      预受理单ID
     * @param orderNo 正式订单票号
     * @return
     * @throws Exception
     */
    @Override
    public Object getOrderInfo(String code, String id, String orderNo, String orderBillMasterId) throws Exception {
        Long begin = System.currentTimeMillis();//开始时间
        // 如果ID不等于空的话 验证并更新订单支付到F6平台
        if (StringUtil.isNotEmpty(id) && StringUtil.isNotEmpty(orderBillMasterId)) {
            Order order = new Order();
            order.setId(Long.parseLong(id));
            order.setOrderBillMasterId(orderBillMasterId);
            iPayOrderService.validatePayOrderPayState(order);
        }

        Object resultOrder = null;
        if (StringUtil.isNotEmpty(orderNo)) {
            //如果是F6系统，则帐套名称和组织代码必须传
            Company company = iCompanyInfoService.getCompanyByCode(code);
            String url = company.getUrl() + "/orderBaseInfo/getOrderInfoByOrderNo?orderNo=" + orderNo;
            if (StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())) {
                url += "&accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
            }
            //请求处理
            String result = null;
            try {
                result = HttpUtil.get(url);
                Long end = System.currentTimeMillis();//结束时间
                System.out.print("运单详情请求F6用时：" + (end - begin) + "毫秒。");
                if (StringUtil.isNotEmpty(result)) {
                    ResultModel model = JSON.parseObject(result, ResultModel.class);
                    if (200 == model.getCode()) {
                        if ("SUCCESS".equals(model.getMsg())) {
                            Map<String, Object> resultMap = (Map<String, Object>) model.getContent();
                            resultOrder = getOrderPayState(null, resultMap, code, orderBillMasterId);
                        } else {
                            throw new Exception("查询运单详情失败！" + model.getMsg());
                        }
                    } else {
                        throw new Exception("查询运单详情失败！" + model.getMsg());
                    }
                } else {
                    throw new Exception("请求业务系统失败或无返回值！");
                }
            } catch (JSONException e) {
                throw new Exception("请求业务系统出错，请联系管理员！", e);
            } catch (SocketTimeoutException e) {
                throw new Exception("请求业务系统超时，请联系管理员！", e);
            } catch (Exception e) {
                throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
            }
        } else {
            Order order = orderMapper.selectByPrimaryKey(Long.valueOf(id));
            resultOrder = getOrderPayState(order, null, code, orderBillMasterId);
        }
        return resultOrder;
    }

    public Object getOrderPayState(Order order, Map<String, Object> resultMap, String code, String orderBillMasterId) {
        System.out.println("OrderPayInfomaction param: code=" + code + " orderBillMasterId=" + orderBillMasterId);
        System.out.println("order value: " + (order != null ? order.toString() : ""));
        System.out.println("resultMap value: " + (resultMap != null ? resultMap.toString() : ""));
        Object result = null;
        String tempFreight = "";
        // 1 验证是否查询订单支付状态
        if (order != null) {
            tempFreight = order.getFreight() + "";
        }
        if (resultMap != null) {
            tempFreight = resultMap.get("freight").toString();
        }

        String transportCost = "", totalTransportCost = "", transportCostIsPay = "", transportCostPayTime = "", transportCostRefundMoney = "", transportCostRefundStatus = "", transportCostRefundTime = "";
        String priceDifferences = "", priceDifferencesIsPay = "", priceDifferencesPayTime = "", priceDifferencesRefundMoney = "", priceDifferencesRefundStatus = "", priceDifferencesRefundTime = "";
        String hBackupMoney1 = "";
        // 访问订单查询状态接口
        if (StringUtil.isNotEmpty(orderBillMasterId)) {
            Map<String, Object> orderInfomaction = getOrderF6PayStateInfomaction(code, orderBillMasterId);
            if (orderInfomaction != null && !orderInfomaction.isEmpty()) {
                // transportCost = orderInfomaction.get("transportCost") != null ? orderInfomaction.get("transportCost").toString() : "";
                transportCost = orderInfomaction.get("totalTransportCost") != null ? orderInfomaction.get("totalTransportCost").toString() : "";
                if (StringUtil.isEmpty(transportCost)) {
                    transportCost = tempFreight;
                }
                transportCostIsPay = orderInfomaction.get("transportCostIsPay") != null ? orderInfomaction.get("transportCostIsPay").toString() : "";
                transportCostPayTime = orderInfomaction.get("transportCostPayTime") != null ? orderInfomaction.get("transportCostPayTime").toString() : "";
                transportCostRefundMoney = orderInfomaction.get("transportCostRefundMoney") != null ? orderInfomaction.get("transportCostRefundMoney").toString() : "";
                transportCostRefundStatus = orderInfomaction.get("transportCostRefundStatus") != null ? orderInfomaction.get("transportCostRefundStatus").toString() : "";
                transportCostRefundTime = orderInfomaction.get("transportCostRefundTime") != null ? orderInfomaction.get("transportCostRefundTime").toString() : "";

                hBackupMoney1 = orderInfomaction.get("hBackupMoney1") != null ? orderInfomaction.get("hBackupMoney1").toString() : "";
                priceDifferences = orderInfomaction.get("priceDifferences") != null ? orderInfomaction.get("priceDifferences").toString() : "";
                priceDifferencesIsPay = orderInfomaction.get("priceDifferencesIsPay") != null ? orderInfomaction.get("priceDifferencesIsPay").toString() : "";
                priceDifferencesPayTime = orderInfomaction.get("priceDifferencesPayTime") != null ? orderInfomaction.get("priceDifferencesPayTime").toString() : "";
                priceDifferencesRefundMoney = orderInfomaction.get("priceDifferencesRefundMoney") != null ? orderInfomaction.get("priceDifferencesRefundMoney").toString() : "";
                priceDifferencesRefundStatus = orderInfomaction.get("priceDifferencesRefundStatus") != null ? orderInfomaction.get("priceDifferencesRefundStatus").toString() : "";
                priceDifferencesRefundTime = orderInfomaction.get("priceDifferencesRefundTime") != null ? orderInfomaction.get("priceDifferencesRefundTime").toString() : "";
            }
        }

        System.out.println("1 moneyInfomaction: transportCost=" + transportCost + " totalTransportCost:" + totalTransportCost + " transportCostIsPay=" + transportCostIsPay + " transportCostPayTime=" + transportCostPayTime);
        System.out.println("2 moneyInfomaction: transportCostRefundMoney=" + transportCostRefundMoney + " transportCostRefundStatus=" + transportCostRefundStatus + " transportCostRefundTime=" + transportCostRefundTime);
        System.out.println("3 moneyInfomaction: priceDifferences=" + priceDifferences + " priceDifferencesIsPay=" + priceDifferencesIsPay + " priceDifferencesPayTime=" + priceDifferencesPayTime);
        System.out.println("4 moneyInfomaction: priceDifferencesRefundMoney=" + priceDifferencesRefundMoney + " priceDifferencesRefundStatus=" + priceDifferencesRefundStatus + " priceDifferencesRefundTime=" + priceDifferencesRefundTime);
        System.out.println("5 moneyInfomaction: hBackupMoney1=" + hBackupMoney1);

        Double orderFreight = 0D;
        Double orderPriceDifference = 0D;

        if (order != null) {
            order.setTransportCost(transportCost);
            order.setTransportCostIsPay(transportCostIsPay);
            order.setTransportCostPayTime(transportCostPayTime);
            order.setTransportCostRefundMoney(transportCostRefundMoney);
            order.setTransportCostRefundStatus(transportCostRefundStatus);
            order.setTransportCostRefundTime(transportCostRefundTime);
            // 差额支付与退款信息
            order.setPriceDifferences(priceDifferences);
            order.setPriceDifferences(hBackupMoney1);
            order.setPriceDifferencesIsPay(priceDifferencesIsPay);
            order.setPriceDifferencesPayTime(priceDifferencesPayTime);
            order.setPriceDifferencesRefundMoney(priceDifferencesRefundMoney);
            order.setPriceDifferencesRefundStatus(priceDifferencesRefundStatus);
            order.setPriceDifferencesRefundTime(priceDifferencesRefundTime);

            orderFreight = order.getFreight();
            orderPriceDifference = order.getPriceDifference();

            result = order;
        } else {
            resultMap.put("transportCost", transportCost);
            resultMap.put("transportCostIsPay", transportCostIsPay);
            resultMap.put("transportCostPayTime", transportCostPayTime);
            resultMap.put("transportCostRefundMoney", transportCostRefundMoney);
            resultMap.put("transportCostRefundStatus", transportCostRefundStatus);
            resultMap.put("transportCostRefundTime", transportCostRefundTime);
            resultMap.put("priceDifferences", priceDifferences);
            resultMap.put("priceDifferences", hBackupMoney1);
            resultMap.put("priceDifferencesIsPay", priceDifferencesIsPay);
            resultMap.put("priceDifferencesPayTime", priceDifferencesPayTime);
            resultMap.put("priceDifferencesRefundMoney", priceDifferencesRefundMoney);
            resultMap.put("priceDifferencesRefundStatus", priceDifferencesRefundStatus);
            resultMap.put("priceDifferencesRefundTime", priceDifferencesRefundTime);
            result = resultMap;
        }
        return result;
    }


    /**
     * 获取F6平台中 订单支付信息
     *
     * @param code
     * @param orderBillMasterId
     * @return
     */
    @Override
    public Map<String, Object> getOrderF6PayStateInfomaction(String code, String orderBillMasterId) {
        Map<String, Object> result = null;
        Company company = iCompanyInfoService.getCompanyByCode(code);
        if (company != null) {
            try {
                // 1 访问接口获取订单数据
                String url = company.getUrl() + "/orderBaseInfo/getPreOrderListPage?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
                url += "&param={\"flag\":0,\"code\":\"" + code + "\",\"pageSize\":10,\"currentPage\":1,\"orderBillMasterId\":" + orderBillMasterId + "}";
                String resultInfo = HttpClientUtils.getUri(url, null);
                log.info("getPreOrderListPage:result:"+resultInfo);
                // 2 判断解析接口数据 并返回F6端数据详细信息
                if (StringUtil.isNotEmpty(resultInfo)) {
                    // 验证接口访问状态
                    Map<String, Object> resultMap = JSON.parseObject(resultInfo);
                    if ("200".equals(resultMap.get("code").toString())) {
                        Map<String, Object> contentMap = JSON.parseObject(resultMap.get("content").toString());
                        if (contentMap != null && !contentMap.isEmpty()) {
                            List<Map> resultList = JSON.parseObject(resultMap.get("content").toString()).getJSONArray("list").toJavaList(Map.class);
                            if (resultList != null && resultList.size() > 0) {
                                result = resultList.get(0);
                            }
                        }
                    }
                }
                System.out.println("url address：" + url);
                System.out.println("F6根据orderBillMasterId获取订单信息：" + resultInfo);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取开票地点
     *
     * @param code 金融代码
     * @return
     */
    @Override
    public List<Map<String, Object>> getPlaceOfLoadingList(String code, String longitude, String latitude) throws Exception {
        // 1.金融代码
        // 2.用户手机定位的经度：longitude（用于实时计算用户与企业的距离）
        // 3.用户手机定位的纬度：latitude （用于实时计算用户与企业的距离）
        Company company = iCompanyInfoService.getCompanyByCode(code);
        if (StringUtil.isEmpty(code)) {
            throw new Exception("金融代码为空");
        }
        if (company == null) {
            throw new Exception("金融代码[" + code + "]对应的公司不存在或已删除");
        }
        List<Map<String, Object>> result = Lists.newArrayList();
        //获取所有子公司信息
        List<TbCompany> list = null;//
        //20200414 lml 改成http方式请求腾云获取公司信息
        try {
            Map<String, String> paramsNew = Maps.newHashMap();
            paramsNew.put("companyCode", company.getCode());
            paramsNew.put("passWord", MD5Util.getMD5Code(company.getTenantPass()));
            paramsNew.put("parentId", company.getId() + "");
            String resultT = HttpClientUtils.post(StaticUtil.restSearchURL + "/privilegeManager/selectByParentId", paramsNew, setHeader(), 20000, 20000);
            if (resultT != null) {
                JSONObject j = JSON.parseObject(resultT);
                String object = j.get("object") + "";
                list = JSON.parseArray(object, TbCompany.class);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        //设置距用户的距离
        setDistance(result, list, longitude, latitude);
        return result;
    }

    /**
     * 设置企业距用户的距离
     *
     * @param list
     * @param longitudeStr
     * @param latitudeStr
     */
    private void setDistance(List<Map<String, Object>> result, List<TbCompany> list, String longitudeStr, String latitudeStr) {
        Double longitude = Double.valueOf(longitudeStr);
        Double latitude = Double.valueOf(latitudeStr);
        if (list != null && list.size() > 0) {
            Map<String, Object> map = null;
            for (TbCompany model : list) {
                map = Maps.newHashMap();
                map.put("companyName", model.getCompanyName());
                //map.put("companyName",model.getCompanyNameAlias());
                if (longitude != null && latitude != null && model.getLongitude() != null && model.getLatitude() != null) {
                    map.put("distance", GoogleMapHelper.getDistance(longitude, latitude, model.getLongitude(), model.getLatitude()));
                } else {
                    map.put("distance", "");
                }
                result.add(map);
            }
        }

        sort(result);
    }

    private void sort(List<Map<String, Object>> list) {
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String distance1 = o1.get("distance").toString();
                String distance2 = o2.get("distance").toString();
                return distance2.compareTo(distance1);
            }
        });
    }

    private List<Order> copyList(List<Map<String, Object>> list) {
        List<Order> orderList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(list)) {
            return orderList;
        }
        Order order = null;
        for (Map<String, Object> map : list) {
            order = new Order();
            //票号
            order.setOrderNumber(map.get("shippingNoteNumber") == null ? "" : map.get("shippingNoteNumber").toString());
            //手工单号
            order.setManualNumber(map.get("originalDocumentNumber") == null ? "" : map.get("originalDocumentNumber").toString());
            //货号
            order.setGoodsNumber(map.get("goodsSelfNumber") == null ? "" : map.get("goodsSelfNumber").toString());
            //开票日期
            order.setOrderCreateTime(DateUtil.turnStringToDate(map.get("consignmentDateTime").toString(), "yyyy-MM-dd"));

            //发货人姓名
            order.setSender(map.get("consignorName") == null ? "" : map.get("consignorName").toString());
            //发货人手机
            order.setSenderMobile(map.get("consignorTelephoneNumber") == null ? "" : map.get("consignorTelephoneNumber").toString());
            //银行卡号
            order.setBankCardNumber(map.get("bankCardNo") == null ? "" : map.get("bankCardNo").toString());
            //开户行名称
            order.setBankName(map.get("bankCardName") == null ? "" : map.get("bankCardName").toString());

            //收货人姓名
            order.setReceiver(map.get("consigneeName") == null ? "" : map.get("consigneeName").toString());
            //收货人手机
            order.setReceiverMobile(map.get("consigneeTelephoneNumber") == null ? "" : map.get("consigneeTelephoneNumber").toString());

            orderList.add(order);
        }
        return orderList;
    }

    private List<Order> toOrderList(List<Map<String, Object>> list) {
        List<Order> orderList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(list)) {
            return orderList;
        }
        Order order = null;
        for (Map<String, Object> map : list) {
            order = new Order();
            Map<String, Object> body = Maps.newHashMap();
            body = JSON.parseObject(map.get("body").toString());
            //票号
            order.setOrderNumber(body.get("shippingNoteNumber") == null ? "" : body.get("shippingNoteNumber").toString());
            //手工单号
            order.setManualNumber(body.get("originalDocumentNumber") == null ? "" : body.get("originalDocumentNumber").toString());
            //货号
            order.setGoodsNumber(body.get("goodsSelfNumber") == null ? "" : body.get("goodsSelfNumber").toString());
            //开票日期
            order.setOrderCreateTime(DateUtil.turnStringToDate(body.get("consignmentDateTime").toString(), "yyyy-MM-dd"));

            Map<String, Object> consignorInfo = Maps.newHashMap();
            consignorInfo = JSON.parseObject(map.get("consignorInfo").toString());

            //发货人姓名
            order.setSender(consignorInfo.get("consignorName") == null ? "" : consignorInfo.get("consignorName").toString());
            //发货人手机
            order.setSenderMobile(consignorInfo.get("consignorTelephoneNumber") == null ? "" : consignorInfo.get("consignorTelephoneNumber").toString());
            //银行卡号
            order.setBankCardNumber(consignorInfo.get("bankCardNo") == null ? "" : consignorInfo.get("bankCardNo").toString());
            //开户行名称
            order.setBankName(consignorInfo.get("bankCardName") == null ? "" : consignorInfo.get("bankCardName").toString());
            //始发地
            order.setPlaceOfLoading(consignorInfo.get("placeOfLoading") == null ? "" : consignorInfo.get("placeOfLoading").toString());

            Map<String, Object> consigneeInfo = Maps.newHashMap();
            consigneeInfo = JSON.parseObject(map.get("consigneeInfo").toString());

            //收货人姓名
            order.setReceiver(consigneeInfo.get("consigneeName") == null ? "" : consigneeInfo.get("consigneeName").toString());
            //收货人手机
            order.setReceiverMobile(consigneeInfo.get("consigneeTelephoneNumber") == null ? "" : consigneeInfo.get("consigneeTelephoneNumber").toString());
            //目的地
            order.setUnloadPlace(consigneeInfo.get("goodsReceiptPlace") == null ? "" : consigneeInfo.get("goodsReceiptPlace").toString());

            orderList.add(order);
        }
        return orderList;
    }

    private List<Order> copyListForBSOrF6(List<Map<String, Object>> list) {
        List<Order> orderList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(list)) {
            return orderList;
        }
        Order order = null;
        for (Map<String, Object> map : list) {
            order = new Order();
            //票号
            order.setOrderNumber(map.get("PH") == null ? "" : map.get("PH").toString());
            //货号
            order.setGoodsNumber(map.get("HH") == null ? "" : map.get("HH").toString());
            //开票地点
            order.setPlaceOfLoading(map.get("KPDD") == null ? "" : map.get("KPDD").toString());
            //发货公司
            order.setSendCompany(map.get("FHGS") == null ? "" : map.get("FHGS").toString());
            //到货公司
            order.setReceiveCompany(map.get("DHGS") == null ? "" : map.get("DHGS").toString());
            //卸货地点
            order.setUnloadPlace(map.get("XHDD") == null ? "" : map.get("XHDD").toString());
            //开票日期
            order.setCreateDate(DateUtil.turnDateToString(DateUtil.turnStringToDate(map.get("KPRQ").toString(), "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd"));

            //发货人姓名
            order.setSender(map.get("FHR") == null ? "" : map.get("FHR").toString());
            //发货人手机
            order.setSenderMobile(map.get("FHRSJ") == null ? "" : map.get("FHRSJ").toString());
            //银行卡号
            order.setBankCardNumber(map.get("BANKCARD") == null ? "" : map.get("BANKCARD").toString());
            //开户行名称
            order.setBankName(map.get("BANKNAME") == null ? "" : map.get("BANKNAME").toString());

            //收货人姓名
            order.setReceiver(map.get("SHR") == null ? "" : map.get("SHR").toString());
            //收货人手机
            order.setReceiverMobile(map.get("SHRSJ") == null ? "" : map.get("SHRSJ").toString());

            //处理状态
            order.setStatus(map.get("ZT") == null ? "" : map.get("ZT").toString());
            order.setGenerateFlag(true);
            order.setOrderBillMasterId(map.get("orderBillMasterId") == null ? "" : map.get("orderBillMasterId").toString());

            // 运费-支付状态与支付金额
            order.setTransportCost(map.get("transportCost") == null ? "" : map.get("transportCost").toString());
            order.setTransportCostIsPay(map.get("transportCostIsPay") == null ? "" : map.get("transportCostIsPay").toString());
            order.setTransportCostPayTime(map.get("transportCostPayTime") == null ? "" : map.get("transportCostPayTime").toString());
            order.setTransportCostRefundStatus(map.get("transportCostRefundStatus") == null ? "" : map.get("transportCostRefundStatus").toString());
            order.setTransportCostRefundMoney(map.get("transportCostRefundMoney") == null ? "" : map.get("transportCostRefundMoney").toString());
            order.setTransportCostRefundTime(map.get("transportCostRefundTime") == null ? "" : map.get("transportCostRefundTime").toString());

            // 差额-支付状态与支付金额
            order.setPriceDifferences(map.get("priceDifferences") == null ? "" : map.get("priceDifferences").toString());
            order.setPriceDifferencesIsPay(map.get("priceDifferencesIsPay") == null ? "" : map.get("priceDifferencesIsPay").toString());
            order.setPriceDifferencesRefundStatus(map.get("priceDifferencesRefundStatus") == null ? "" : map.get("priceDifferencesRefundStatus").toString());
            order.setPriceDifferencesRefundMoney(map.get("priceDifferencesRefundMoney") == null ? "" : map.get("priceDifferencesRefundMoney").toString());
            order.setPriceDifferencesRefundTime(map.get("priceDifferencesRefundTime") == null ? "" : map.get("priceDifferencesRefundTime").toString());
            order.setPriceDifferencesPayTime(map.get("priceDifferencesPayTime") == null ? "" : map.get("priceDifferencesPayTime").toString());

            orderList.add(order);
        }
        return orderList;
    }

    /**
     * 我的运单
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<Order> getAllOrderListFromBusinessSys(Map<String, Object> params) throws Exception {
        List<Order> result = null;
        //是否受理
        if ("1".equals(params.get("generateFlag").toString())) {
            //已受理
            result = getOrderListFromBusinessSys(params);
        } else {
            //未受理
            result = getPreOrderListFromBusinessSys(params);
        }
        // 查询订单支付订单状态，更新支付订单信息
        // iPayOrderService.vaildateOrderPayStateService(result);
        return result;
    }

    /**
     * 我的运单
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public List<Order> getMyAllOrderList(Map<String, Object> params) throws Exception {
        // 初始化返回值
        List<Order> list = Lists.newArrayList();
        //如果开始日期和结束为空，则默认查询一个月的数据
        if (params.get("startDate") != null && StringUtil.isNotEmpty(params.get("startDate").toString())) {
            params.put("startDate", params.get("startDate") + " 00:00:00");
        }
        if (params.get("endDate") != null && StringUtil.isNotEmpty(params.get("endDate").toString())) {
            params.put("endDate", params.get("endDate") + " 23:59:59");
        }
        //请求处理
        String result = null;
        try {
            list = orderMapper.queryMyOrderList(params);
            if (list == null) {
                throw new Exception("BS服务端失败或无返回值！");
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
        }
        return list;
    }

    @Override
    public Integer deleteNotRegularById(Order order) {
        return orderMapper.deleteNotRegularById(order);
    }

    @Override
    public Order selectById(Long id) {
        return orderMapper.selectById(id);
    }

    @Override
    public ResultModel searchOrderNumberList(Map<String, Object> params) throws Exception {
        Long begin = System.currentTimeMillis();//开始时间

        //输入框值
        String orderNumber = params.get("orderNumber").toString();
        //查询条件类型
        String type = params.get("type").toString();

        //根据金融代码获取公司信息，如果获取不到，抛出异常
        Company company = iCompanyInfoService.getCompanyByCode(params.get("code").toString());
        if (company == null) {
            return ResultModel.error("该企业[" + params.get("code").toString() + "]已被删除！");
        }

        //请求地址(如果是F6系统，则帐套名称和组织代码必须传)
        String url = company.getUrl() + "/goodsTraces/getGoodsTracesByOrderNo?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        if(StringUtil.isEmpty(orderNumber)){
            return ResultModel.error("输入栏不能输入空值");
        }

        if(StringUtil.isNotEmpty(type)){
            if(type.equals("1")){ //票号
                url += "&orderNo=" + orderNumber;
            }else if(type.equals("2")){ // 货号
                url += "&goodsNumber=" + orderNumber;
            }else if(type.equals("3")){ //货号序号
                url += "&goodsNumberOrder=" + orderNumber;
            }else{ //其他情况（其他情况直接返回）
                return ResultModel.error("查询条件选择错误");
            }
        }else{
            return ResultModel.error("查询条件type值为空");
        }

        //请求处理
        String result = null;
        try {
            System.out.println("searchOrderNumberList url:" + url );
            result = HttpClientUtils.post(url, null, setHeader(), 20000, 20000);
            log.info("getPreOrderListPage:result:"+result);
            Long end = System.currentTimeMillis();//结束时间
            System.out.print("查询货运单请求F6用时：" + (end - begin) + "毫秒。");
            if (StringUtil.isNotEmpty(result)) {
                Map<String, Object> resultMap = JSON.parseObject(result);
                if ("SUCCESS".equals(resultMap.get("msg").toString())) {
//                    list = JSON.parseObject(resultMap.get("content").toString()).getJSONArray("list").toJavaList(Order.class);
                    return ResultModel.ok(resultMap);
                } else {
                    return ResultModel.error("从F6或BS服务端获取最新的10条受理单失败！" + resultMap.get("msg").toString());
                }
            } else {
                return ResultModel.error("请求F6或BS服务端失败或无返回值！");
            }
        } catch (JSONException e) {
            log.info("请求F6或BS服务端出错，请联系管理员！", e);
            return ResultModel.error("请求F6或BS服务端出错，请联系管理员！");
        } catch (SocketTimeoutException e) {
            log.info("请求F6或BS服务端出错，请联系管理员！", e);
            return ResultModel.error("请求F6或BS服务端超时，请联系管理员！");
        } catch (Exception e) {
            log.info(e.getMessage() == null ? "服务端出错！" : e.getMessage(), e);
            return ResultModel.error("请求服务端出错！");
        }
    }

    @Override
    public List<String> getGoodsNameInfoBSOrF6(String code,Company company) throws Exception {
        List<String> goodsNameList = new ArrayList<>();

        //如果是F6系统，则帐套名称和组织代码必须传
        if(company==null){
            company = iCompanyInfoService.getCompanyByCode(code);
        }

        if (company == null || StringUtil.isEmpty(company.getUrl())) {
            throw new Exception("该企业[" + code + "]已被删除！");
        }
        //拼装请求URL
        String url = company.getUrl() + "/orderBaseInfo/getGoodsNameInfo?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
       log.info("常用货物名称："+url);
        //请求处理
        String result = HttpUtil.get(url);
        if (StringUtil.isNotEmpty(result)) {
            ResultModel model = JSON.parseObject(result, ResultModel.class);
            if (200 == model.getCode() && "SUCCESS".equals(model.getMsg())) {
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) model.getContent();
                for(Map<String, Object> m : mapList) {
                    goodsNameList.add(m.get("goodsName").toString());
                }
            }
        }

        return goodsNameList;
    }
}
